<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('channel.channelInfo')"
    custom-class="dialog-min-width"
    @close="onDialogClose"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formEdit" :rules="rules" label-width="120px">
      <el-row>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('channel.name')" prop="name">
            <el-input v-model="formEdit.name" maxlength="32" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('channel.parentId')">
            <el-tree-select
              ref="channelRef"
              v-model="parentChannelId"
              :data="parentChannels"
              :render-after-expand="false"
              @current-change="handleChannelChange"
              node-key="channelId"
              check-strictly
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item prop="levelCode">
            <template #label>
              {{ t("channel.levelCode") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                trigger="click"
                :content="t('channel.levelCodeContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-input v-model="formEdit.levelCode" maxlength="64" clearable>
              </el-input
            ></template>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24"></el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('channel.homeMenu')">
            <el-switch
              v-model="formEdit.homeMenu"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24"></el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('channel.featuredChannel')">
            <el-switch
              v-model="formEdit.featuredChannel"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item>
            <template #label>
              {{ t("channel.singleChannel") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                :content="t('channel.singleChannelContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-switch
                v-model="formEdit.singleChannel"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-form-item>
        </el-col>

        <el-col
          v-if="formEdit.featuredChannel == 1"
          :lg="24"
          :md="24"
          :sm="24"
          :xs="24"
        >
          <el-form-item :label="t('channel.featuredChannelImage')">
            <el-upload
              ref="logoFileRef"
              v-model:file-list="logoFileList"
              accept=".jpg,.jpeg,.png,.gif"
              :action="apiUpload.uploadUrl()"
              :headers="headers()"
              :data="{
                businessKey: formEdit.channelId,
                category: logoFileCategory,
              }"
              :limit="1"
              :before-upload="handleLogoBeforeUpload"
              :on-preview="handleLogoUploadPreview"
              :on-exceed="handleLogoUploadExceed"
              :on-success="handleLogoUploadSuccess"
              list-type="picture-card"
              ><el-icon><Plus /></el-icon
              ><template #tip>
                <div class="el-upload__tip">
                  {{ t("upload.imgTip", { size: 100 }) }}
                </div>
              </template></el-upload
            >
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24"></el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('channel.status')">
            <el-switch
              v-model="formEdit.status"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('channel.description')">
            <el-input
              v-model="formEdit.description"
              type="textarea"
              maxlength="64"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item>
            <template #label>
              {{ t("channel.authorizedOrg") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                trigger="click"
                :content="t('channel.authorizedOrgContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-tree
                ref="channelOrgsRef"
                style="max-width: 400px"
                :data="orgList"
                show-checkbox
                node-key="value"
                :default-expanded-keys="expandedOrgs"
                :default-checked-keys="checkedOrgs"
              />
            </template>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from "vue";
import { Warning } from "@element-plus/icons-vue";
import { useStore } from "../../../stores/store";
import utils from "../../../utils/utils";
import { Plus } from "@element-plus/icons-vue";
import { headers } from "../../../utils/request";
import apiUpload from "../../admin/api/upload";
import apiCms from "../api/cms";
import { useI18n } from "vue-i18n";
import apiOrganization from "../../admin/api/organization";
const { t } = useI18n({ useScope: "global" });
const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const store = useStore();
const formRef = ref();
const channelRef = ref();
const channelOrgsRef = ref();

const stateOriginal = () =>
  reactive({
    dialogFormVisible: false,
  });
const state = reactive(stateOriginal());

// 父节点
const parentChannels = ref([]);
// 解决没有上级栏目，parentId == 0 时界面显示 0 的问题
const parentChannelId = ref("");
// 全部组织机构
const orgList = ref();
// 服务器返回的默认选中的组织机构
const checkedOrgs = ref([]);
// 默认展开一级组织机构
const expandedOrgs = ref([]);

const logoFileRef = ref();
const logoFileCategory = "cms-channel-logo";
const logoFileList = ref([]);

const formEditOriginal = () => {
  return {
    channelId: "",
    levelCode: "",
    name: "",
    parentId: "0",
    homeMenu: 1,
    featuredChannel: 0,
    featuredChannelImageFile: "",
    singleChannel: 0,
    status: 1,
    description: "",
    // 前台操作选中的
    orgCodes: Array<any>(),
    fileIds: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  orderIndex: [
    {
      required: true,
      message: () => t("channel.orderIndex"),
      trigger: "blur",
    },
  ],
  name: [{ required: true, message: () => t("channel.name"), trigger: "blur" }],
});

const handleChannelChange = (currentNode: any, prevNode: any) => {
  // console.log(currentNode, currentNode.label);
  const node = channelRef.value.getCurrentNode();
  if (node != null) {
    // console.log("子节点", node.label);
    // 子节点
    formEdit.parentId = node.channelId;
  }
};

const handleLogoBeforeUpload = (file: any) => {
  if (file.type.indexOf("image/") == -1) {
    // console.log("handleLogoBeforeUpload", file, logoFileList.value);
    // utils.infoNotification(t("common.submitSuccess"));
    utils.infoNotification(t("upload.imgType"));
    return false;
  }
  // console.log("file.size", file.size);
  // byte
  if (file.size / 1024 < 100) {
    // 上传图片应小于100K，请重新上传
    utils.infoNotification(t("upload.fileSizeGreater", { size: 100 }));
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    utils.infoNotification(t("upload.fileSizeLessMB", { size: 5 }));
    return false;
  }
};
const handleLogoUploadPreview = (file: any) => {
  // todo 统一预览页面
  // console.log("handleLogoUploadPreview", file);
  window.open(apiUpload.downloadUrl(file.uid));
};
const handleLogoUploadExceed = (files: any) => {
  // 超过限制数量自动替换旧文件
  // console.log("handleLogoUploadExceed", files);
  logoFileRef.value!.clearFiles();
  const file = files[0] as any;
  logoFileRef.value!.handleStart(file);
  logoFileRef.value!.submit();
};
const handleLogoUploadSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any
) => {
  if (response.code == 200) {
    // 更新服务器端主键
    uploadFile.uid = response.data.fileId;
  }
};

const handleSubmit = async () => {
  await formRef.value.validate();

  if (parentChannelId.value == "") {
    formEdit.parentId = "0";
  }
  if (formEdit.parentId == formEdit.channelId) {
    utils.warningNotification("不能选择自己做为上级栏目");
    return;
  }

  // (leafOnly) 接收一个布尔类型参数，默认为 false. 如果参数是 true, 它只返回当前选择的子节点数组。
  const checkedCodes = channelOrgsRef.value.getCheckedKeys(true);
  checkedCodes.forEach((m) => {
    formEdit.orgCodes.push(m);
  });

  let fileIds = "";
  logoFileList.value.forEach((file) => {
    fileIds += file.uid + ",";
    // 只有一个图
    formEdit.featuredChannelImageFile = file.uid;
  });
  formEdit.fileIds = fileIds;
  if (formEdit.featuredChannel == 0) {
    //不是专题栏目时，没有图
    formEdit.fileIds = "";
    formEdit.featuredChannelImageFile = "";
  }

  apiCms
    .saveChannel(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      // 还原原文
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = async (row: any) => {
  Object.assign(formEdit, formEditOriginal());
  checkedOrgs.value.splice(0);
  expandedOrgs.value.splice(0);
  logoFileList.value = [];
  parentChannels.value = [];
  parentChannelId.value = "";

  await apiCms
    .loadAllChannelJson()
    .then((response: any) => {
      if (response.data.code == 200) {
        // Object.assign(parentChannels, response.data.data);
        response.data.data.forEach((m) => {
          parentChannels.value.push(m);
        });
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });

  await apiOrganization
    .loadAllOrganizationJson("")
    .then((response: any) => {
      if (response.data.code == 200) {
        orgList.value = response.data.data;
        response.data.data.forEach((m) => {
          expandedOrgs.value.push(m.value);
        });
        // console.log("expandedOrgs.value", expandedOrgs.value);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });

  if (row != undefined) {
    // 等待 channelOrgs 选中节点处理完
    await apiCms
      .getChannel(row.channelId)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);
          if (formEdit.parentId != "0") {
            parentChannelId.value = formEdit.parentId;
          }
          response.data.channelOrgs.forEach((m) => {
            checkedOrgs.value.push(m.orgCode);
          });

          response.data.attachFiles.forEach((file) => {
            logoFileList.value.push({
              uid: file.fileId,
              name: file.fileName,
              url: apiUpload.downloadUrl(file.fileId),
            });
          });
          // console.log("channelOrgs", channelOrgs);
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  } else {
    // 初始化id
    apiCms
      .generateId()
      .then((response: any) => {
        if (response.data.code == 200) {
          formEdit.channelId = response.data.data;
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  }

  //   if (row != undefined) {
  //     // 修改
  //     state.addAccount = false;
  //     let model = null;
  //     apiAccount
  //       .getAccount(row.accountId)
  //       .then((response: any) => {
  //         if (response.data.code == 200) {
  //           model = response.data.data;
  //           Object.assign(formEdit, model);
  //         }
  //       })
  //       .catch((err: any) => {
  //         utils.errorNotification(t("common.submitException"), err);
  //       });
  //   } else {
  //     formEdit.accountId = utils.getUUID();
  //     // 查询全部角色
  //   }

  state.dialogFormVisible = true;
  // nextTick(() => {
  //   channelOrgsRef.value.setCheckedKeys(checkedOrgs.value);
  // });
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const onDialogClose = () => {
  // state.deptRefesh = false;
};

defineExpose({
  show,
});
</script>
